package com.fzfnn.scrapbook.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.stream.Collectors;
@Component
public class IpUtil {

    // 获取真实客户端 IP 地址（支持代理）
    public static String getClientIp(HttpServletRequest request) {
        String[] headers = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_CLIENT_IP",
                "HTTP_X_FORWARDED_FOR"
        };
        for (String header : headers) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip.split(",")[0];
            }
        }
        return request.getRemoteAddr();
    }

    public static String getCityInfo(String ip) {
        try {
            if ("127.0.0.1".equals(ip) || "::1".equals(ip)) {
                return "本地地址";
            }

            URL url = new URL("http://ip-api.com/json/" + ip + "?lang=zh-CN");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String response = in.lines().collect(Collectors.joining());
            in.close();

            JSONObject json = JSONObject.parseObject(response);
            if ("success".equals(json.getString("status"))) {
                String region = json.getString("regionName"); // 省
                String city = json.getString("city");         // 市
                return region + city;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "未知地址";
    }

}
